<template>
  <div class="table-form">
    <el-form ref="formRef" :model="form" :inline="true" class="pro-select-box">
      <el-form-item :label="$t('user.userManagement.name')" prop="name">
        <el-input
          v-model="form.name"
          class="form-input"
          clearable
          :placeholder="$t('user.userManagement.name')"
        />
      </el-form-item>
      <el-form-item
        :label="$t('user.userManagement.accountName')"
        prop="userName"
      >
        <el-input
          v-model="form.userName"
          class="form-input"
          clearable
          :placeholder="$t('user.userManagement.accountName')"
        />
      </el-form-item>
      <el-form-item :label="$t('user.userManagement.status')" prop="state">
        <el-select
          v-model="form.state"
          class="form-input"
          :placeholder="$t('user.userManagement.status')"
          clearable
        >
          <el-option
            v-for="item in usableType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="checkList"
          v-permission="['system:user:get']"
          >{{ $t("common.queryText") }}</el-button
        >
        <el-button
          type="primary"
          @click="handlerAdd"
          v-permission="['system:user:add']"
          >{{ $t("common.add") }}</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <hcTable
      :table-data="tableData"
      :options="tableOptions"
      :columns="tableColumn"
      @command="handleAction"
      @size-change="handlerPageSize"
      @current-change="handlerPageIndex"
    >
      <template #state="{ row }">
        <div class="flex-a-c">
          <div
            class="state-icon"
            :class="[row.state ? 'state-start' : 'state-stop']"
          ></div>
          <span style="padding-left: 8px">{{
            row.state ? $t("common.enable") : $t("common.disable")
          }}</span>
        </div>
      </template>
      <template #sex="{ row }">
        {{
          row.sex === 0
            ? $t("user.userManagement.male")
            : row.sex === 1
              ? $t("user.userManagement.female")
              : $t("user.userManagement.unknown")
        }}
      </template>
      <template #creationTime="{ row }">
        {{ formatTime(row.creationTime) }}
      </template>
    </hcTable>
    <!-- 新增、编辑用户弹框 -->
    <user-dialog :options="options" @onCancel="closeDialog" @onSure="onSure" />
    <!-- 重置密码弹框 -->
    <reset-pwd-dialog
      :show="resetPwdShow"
      :curUser="curUser"
      @onCancel="(resetPwdShow = false), (curUser = {})"
      @onSure="handlerReset"
    />
  </div>
</template>

<script setup name="UserManageHome">
import { reactive, ref, toRefs, computed } from "vue";
import userStore from "@/store/userStore";
import { ElMessage, ElMessageBox } from "element-plus";
import useTable from "@/hooks/useTable";
import { formatTime } from "@/utils";
import UserDialog from "./components/user-dialog.vue";
import resetPwdDialog from "./components/reset-pwd-dialog.vue";
import { resetPwdApi } from "@/api/auth";
import useAuths from "@/hooks/useAuths";
import { useI18n } from "vue-i18n";

const { t: $t } = useI18n();

const { getUserInfo } = useAuths();

const store = userStore();

const {
  list,
  total,
  loading,
  getList,
  addFun,
  updateFun,
  deleteFun,
  editStateFun,
} = useTable("/User");

const formRef = ref();

// 可用类型
const usableType = [
  { label: $t("common.all"), value: "" },
  { label: $t("common.normal"), value: true },
  { label: $t("common.disable"), value: false },
];

const tableColumn = [
  {
    type: "index",
    width: "50",
    label: "No.",
    align: "center",
    fixed: true,
  },
  {
    prop: "cardId",
    label: $t("user.userManagement.idCard"),
    showOverflowTooltip: true,
  },
  {
    prop: "name",
    label: $t("user.userManagement.name"),
    showOverflowTooltip: true,
    fixed: true,
  },
  {
    prop: "userName",
    label: $t("user.userManagement.accountName"),
    showOverflowTooltip: true,
  },
  {
    prop: "allRoles",
    label: $t("user.userManagement.role"),
    showOverflowTooltip: true,
  },
  {
    prop: "state",
    label: $t("user.userManagement.status"),
    slot: "state",
  },
  {
    prop: "sex",
    label: $t("user.userManagement.gender"),
    slot: "sex",
  },
  {
    prop: "phone",
    label: $t("user.userManagement.phoneNumber"),
    showOverflowTooltip: true,
  },
  {
    prop: "creationTime",
    width: "120",
    label: $t("user.userManagement.createTime"),
    slot: "creationTime",
    showOverflowTooltip: true,
  },
  {
    prop: "remark",
    label: $t("user.userManagement.remark"),
    showOverflowTooltip: true,
  },
  {
    width: "245",
    label: $t("common.operate"),
    align: "center",
    fixed: "right",
    buttons: [
      {
        name: $t("common.resetpdText"),
        type: "primary",
        command: "reset",
        permission: ["system:user:resetpwd"],
      },
      {
        name: $t("common.edit"),
        type: "warning",
        command: "edit",
        permission: ["system:user:edit"],
      },
      {
        name: $t("common.delText"),
        type: "danger",
        command: "delete",
        permission: ["system:user:del"],
      },
    ],
  },
];

const data = reactive({
  // 绑定数据
  form: {
    name: "",
    userName: "",
    phone: "",
    state: "",
  },
  page: {
    pageSize: 10,
    pageIndex: 1,
  },
  options: {
    show: false,
    type: "", // 用于判断是编辑还是删除 add edit
    curUser: null,
  },
  curUser: {}, // 用于重置点击的用户密码
  resetPwdShow: false, // 是否显示重置密码弹框
});

const tableData = computed(() => {
  let arr = [];
  if (list.value.length) {
    arr = list.value.map((item) => {
      item.allRoles =
        item.roles.length && item.roles.map((role) => role.roleName).join(",");
      return item;
    });
  }
  return arr;
});

// 获取用户基本信息
const userInfo = computed(() => {
  return store.authUser;
});

const tableOptions = computed(() => {
  return {
    loading: loading.value,
    showPagination: true,
    // paginationPosition: 'center',
    border: true,
    paginationConfig: {
      total: total.value,
      currentPage: data.page.pageIndex,
      pageSize: data.page.pageSize,
    },
  };
});

const params = computed(() => {
  let form = JSON.parse(JSON.stringify(data.form));
  Object.keys(form).forEach((key) => {
    if (form[key] === null) {
      form[key] = "";
    }
  });
  return {
    ...form,
    ...data.page,
  };
});
// 操作事件
const handleAction = (command, row) => {
  switch (command) {
    case "reset":
      data.curUser = row;
      data.resetPwdShow = true;
      // handlerReset(row.id)
      break;
    case "edit":
      handlerEdit(row);
      break;
    case "delete":
      handlerDel(row.id);
      break;
    default:
      break;
  }
};
// 点击查询
const checkList = () => {
  data.page.pageIndex = 1;
  getList(params.value);
};
// 表请求条数改变
const handlerPageSize = (pageSize) => {
  data.page.pageSize = pageSize;
  data.page.pageIndex = 1;
  getList(params.value);
};
// 表格页数改变
const handlerPageIndex = (pageIndex) => {
  data.page.pageIndex = pageIndex;
  getList(params.value);
};
// 重置密码
const handlerReset = async (res) => {
  let isCurUser = true;
  if (userInfo.value.user.id === res.id) {
    isCurUser = await ElMessageBox.confirm(`是否重置当前用户密码?`, "提示", {
      confirmButtonText: "确 定",
      cancelButtonText: "取 消",
      type: "warning",
    })
      .then(() => {
        return true;
      })
      .catch(() => {
        return false;
      });
  }
  if (!isCurUser) return;
  resetPwdApi(res.id, res.data).then(() => {
    ElMessage({
      message: "重置密码成功",
      type: "success",
      duration: 2000,
    });
  });
};
// 改变可用状态
const changeEnable = (row) => {
  editStateFun({ id: row.id, state: row.state });
};
// 新增
const handlerAdd = () => {
  data.options = {
    show: true,
    type: "add", // 用于判断是编辑还是删除 add edit
    curUser: null,
  };
};
// 编辑
const handlerEdit = async (item) => {
  data.options = {
    show: true,
    type: "edit", // 用于判断是编辑还是删除 add edit
    curUser: item,
  };
};
// 删除
const handlerDel = async (item) => {
  deleteFun([item]);
};
// 保存弹框
const onSure = async (options) => {
  if (options.type === "add") {
    // 新增用户
    addFun(options.form);
  } else {
    await updateFun(options.id, options.form);
    if (userInfo.value.user.id === options.id) {
      getUserInfo();
    }
  }
  closeDialog();
};
// 关闭弹框
const closeDialog = () => {
  data.options = {
    show: false,
    type: "", // 用于判断是编辑还是删除 add edit
    curUser: null,
  };
};

const { form, options, resetPwdShow, curUser } = toRefs(data);
</script>
<style lang="scss" scoped></style>
